# -*- coding: utf-8 -*-
"""
小红书帖子助手 - 图形化界面（文件夹模式）
"""
import asyncio
import os
import tkinter as tk
from tkinter import filedialog, messagebox, ttk
from typing import List, Optional



# 请确保 XiaohongshuPoster 已定义并可导入
from xiaohongshu_poster import XiaohongshuPoster


class XiaohongshuGUI:
    def __init__(self, root: tk.Tk):
        self.root = root
        self.root.title("小红书帖子创作与发布助手")
        self.root.geometry("650x650")
        self.root.minsize(650, 650)  # 设置最小窗口大小
        # 允许用户调整窗口大小

        self.image_folder: Optional[str] = None
        self.image_paths: List[str] = []
        self.theme_path: Optional[str] = None
        self.select_type = "create_and_publish"

        # 模型参数
        
        self.model_name = ""
        self.api_key = ""
        self.base_url = ""

        self.setup_ui()

    def setup_ui(self):
        # 标题
        title_label = tk.Label(self.root, text="小红书帖子助手", font=("Arial", 16, "bold"))
        title_label.pack(pady=10)

        # 图片文件夹选择
        folder_frame = tk.Frame(self.root)
        folder_frame.pack(pady=5, fill="x", padx=20)
        tk.Label(folder_frame, text="选择图片文件夹:", anchor="w").pack(fill="x")
        self.folder_entry = tk.Entry(folder_frame, state="readonly")
        self.folder_entry.pack(fill="x", pady=5)
        tk.Button(folder_frame, text="选择文件夹", command=self.select_image_folder).pack(pady=2)

        # 显示找到的图片
        self.img_preview = tk.Label(self.root, text="未选择文件夹", fg="gray")
        self.img_preview.pack()

        # 主题文件选择
        theme_frame = tk.Frame(self.root)
        theme_frame.pack(pady=5, fill="x", padx=20)
        tk.Label(theme_frame, text="选择主题/内容文件 (.txt):", anchor="w").pack(fill="x")
        self.theme_entry = tk.Entry(theme_frame, state="readonly")
        self.theme_entry.pack(fill="x", pady=5)
        tk.Button(theme_frame, text="选择文件", command=self.select_theme_file).pack(pady=2)

        # 模型参数
        model_frame = tk.LabelFrame(self.root, text="模型参数设置", padx=10, pady=3)
        model_frame.pack(pady=5, fill="x", padx=20)
        
        # Model Name
        model_name_frame = tk.Frame(model_frame)
        model_name_frame.pack(fill="x", pady=1)
        tk.Label(model_name_frame, text="Model Name:", width=12, anchor="w").pack(side="left")
        self.model_name_entry = tk.Entry(model_name_frame)
        self.model_name_entry.insert(0, self.model_name)
        self.model_name_entry.pack(side="left", fill="x", expand=True, padx=(5, 0))
        
        # API Key
        api_key_frame = tk.Frame(model_frame)
        api_key_frame.pack(fill="x", pady=1)
        tk.Label(api_key_frame, text="API Key:", width=12, anchor="w").pack(side="left")
        self.api_key_entry = tk.Entry(api_key_frame, show="*")
        self.api_key_entry.insert(0, self.api_key)
        self.api_key_entry.pack(side="left", fill="x", expand=True, padx=(5, 0))
        
        # Base URL
        base_url_frame = tk.Frame(model_frame)
        base_url_frame.pack(fill="x", pady=1)
        tk.Label(base_url_frame, text="Base URL:", width=12, anchor="w").pack(side="left")
        self.base_url_entry = tk.Entry(base_url_frame)
        self.base_url_entry.insert(0, self.base_url)
        self.base_url_entry.pack(side="left", fill="x", expand=True, padx=(5, 0))
        
        # Base URL提示
        base_url_tip = tk.Label(
            model_frame, 
            text="阿里百炼：https://dashscope.aliyuncs.com/compatible-mode/v1\n智谱AI：https://open.bigmodel.cn/api/paas/v4/\n火山方舟：https://ark.cn-beijing.volces.com/api/v3\n其他兼容OpenAI格式",
            justify="left",
            font=("Arial", 8)
        )
        base_url_tip.pack(side="left", fill="x", expand=True, padx=(5, 0))

        # 操作类型
        type_frame = tk.Frame(self.root)
        type_frame.pack(pady=5, fill="x", padx=20)
        tk.Label(type_frame, text="操作类型:", anchor="w").pack(fill="x")
        self.type_combo = ttk.Combobox(
            type_frame,
            values=["create_and_publish", "publish"],
            state="readonly"
        )
        self.type_combo.set("create_and_publish")
        self.type_combo.pack(fill="x", pady=5)
        self.type_combo.bind("<<ComboboxSelected>>", self.on_type_change)

        # 说明标签
        self.tip_label = tk.Label(
            self.root,
            text="• create_and_publish: 根据主题生成文案并发布\n• publish: 直接发布.txt中的完整内容",
            fg="gray",
            justify="left"
        )
        self.tip_label.pack(pady=(0, 10))

        # 开始按钮
        self.start_btn = tk.Button(
            self.root,
            text="开始执行",
            bg="#4CAF50",
            fg="white",
            font=("Arial", 12),
            command=self.start_task
        )
        self.start_btn.pack(pady=15, fill="x", padx=120)

        # 状态栏
        self.status_var = tk.StringVar(value="就绪")
        status_label = tk.Label(self.root, textvariable=self.status_var, fg="blue")
        status_label.pack(side="bottom", pady=5)

    def select_image_folder(self):
        folder = filedialog.askdirectory(title="选择包含图片的文件夹")
        if folder:
            self.image_folder = folder
            self.folder_entry.config(state="normal")
            self.folder_entry.delete(0, tk.END)
            self.folder_entry.insert(0, folder)
            self.folder_entry.config(state="readonly")

            # 扫描图片
            valid_ext = (".jpg", ".jpeg", ".png", ".JPG", ".JPEG", ".PNG")
            self.image_paths = [
                os.path.join(folder, f)
                for f in os.listdir(folder)
                if f.lower().endswith(valid_ext)
            ]
            self.image_paths.sort()

            if self.image_paths:
                count = len(self.image_paths)
                preview_names = ", ".join([os.path.basename(p) for p in self.image_paths[:3]])
                if count > 3:
                    preview_names += "..."
                self.img_preview.config(text=f"找到 {count} 张图片: {preview_names}", fg="black")
            else:
                self.img_preview.config(text="⚠️ 该文件夹中未找到图片！", fg="red")

    def select_theme_file(self):
        file_path = filedialog.askopenfilename(
            title="选择主题或内容文件",
            filetypes=[("Text Files", "*.txt"), ("All Files", "*.*")]
        )
        if file_path:
            self.theme_path = file_path
            self.theme_entry.config(state="normal")
            self.theme_entry.delete(0, tk.END)
            self.theme_entry.insert(0, file_path)
            self.theme_entry.config(state="readonly")

    def on_type_change(self, event=None):
        mode = self.type_combo.get()
        if mode == "create_and_publish":
            self.tip_label.config(
                text="• create_and_publish: 根据主题生成文案并发布\n（.txt 内容为创作提示，如'西湖美景，春天，汉服'）"
            )
        else:
            self.tip_label.config(
                text="• publish: 直接发布.txt中的完整内容\n（.txt 格式：第一行为标题：XXX，第二行为正文：XXX，第三行为标签：XXX）"
            )

    def start_task(self):
        # 验证输入
        if not self.image_folder or not self.image_paths:
            messagebox.showwarning("警告", "请先选择包含图片的文件夹！")
            return
        if not self.theme_path or not os.path.exists(self.theme_path):
            messagebox.showwarning("警告", "请选择有效的 .txt 文件！")
            return

        self.status_var.set("正在执行...")
        self.start_btn.config(state="disabled")
        self.root.update()

        try:
            with open(self.theme_path, "r", encoding="utf-8") as f:
                theme_content = f.read().strip()

            if not theme_content:
                messagebox.showwarning("警告", ".txt 文件内容为空！")
                return

            asyncio.run(
                self.run_task(
                    image_paths=self.image_paths,
                    theme=theme_content,
                    select_type=self.type_combo.get()
                )
            )
        except Exception as e:
            messagebox.showerror("错误", f"执行失败:\n{str(e)}")
            self.status_var.set("❌ 失败")
        finally:
            self.start_btn.config(state="normal")

    async def run_task(self, image_paths, theme, select_type):
        try:
            # 获取界面输入的模型参数
            model_name = self.model_name_entry.get().strip()
            api_key = self.api_key_entry.get().strip()
            base_url = self.base_url_entry.get().strip()
            
            # 验证模型参数
            if not model_name or not api_key or not base_url:
                messagebox.showwarning("警告", "请填写完整的模型参数！")
                self.status_var.set("❌ 参数缺失")
                return
            
            poster = XiaohongshuPoster()
            result = await poster.create_and_publish_post(
                model_name=model_name,
                api_key=api_key,
                base_url=base_url,
                image_paths=image_paths,
                theme=theme,
                select_type=select_type,
            )
            msg = result.get("message", "操作完成")
            messagebox.showinfo("成功", f"✅ {msg}")
            self.status_var.set("✅ 成功")
        except Exception as e:
            raise e


def main():
    root = tk.Tk()
    app = XiaohongshuGUI(root)
    root.mainloop()


if __name__ == "__main__":
    main()